package com.xinxi11.project.qx.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 测试系统的性能的一个简单过滤器
 */
public class PerformanceFilter implements Filter {

	public static final ThreadLocal<Long> businessPerf = new ThreadLocal<Long>();
	public static final ThreadLocal<Long> daoPerf = new ThreadLocal<Long>();

	private static final String START_TIME = "ST_PERF_FILTER";

	private final Log log = LogFactory.getLog(getClass());

	public void init(FilterConfig config) throws ServletException {
		/* Nothing to do */
	}

	public void destroy() {
		/* Nothing to do */
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String url = HttpUtils.getURL((HttpServletRequest) request);
		if (url.endsWith("/checkState.jspx")) {
			chain.doFilter(request, response);
			return;
		}
		request.setAttribute(START_TIME, Long.valueOf(System.currentTimeMillis()));
		businessPerf.set(Long.valueOf(0));
		daoPerf.set(Long.valueOf(0));
		try {
			chain.doFilter(request, response);
		} finally {
			long httpTime = System.currentTimeMillis()
					- ((Long) request.getAttribute(START_TIME)).longValue();
			long businessTime = businessPerf.get().longValue();
			long daoTime = daoPerf.get().longValue();
			long businessPercent = httpTime == 0 ? 0 : businessTime * 100 / httpTime;
			long daoPercent = httpTime == 0 ? 0 : daoTime * 100 / httpTime;
			// 保存性能信息
			log.info(url + " execution: " + httpTime + "ms.");
			log.info("Business execution: " + businessTime + "ms, " + businessPercent + "%");
			log.info("Dao execution: " + daoTime + "ms, " + daoPercent + "%");
			businessPerf.remove();
			daoPerf.remove();
		}
	}

}
